<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="登录">
      <van-icon
        v-if="$route.query.redirect"
        slot="left"
        class="text"
        name="cross"
        @click="$router.back()"
      />
    </van-nav-bar>
    <!-- /导航栏 -->
    <!-- 登录表单 -->
    <van-form ref="loginForm" @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        name="mobile"
        placeholder="请输入手机号"
        type="number"
        :rules="userFormRules.mobile"
        maxlength="11"
      >
        <template v-slot:left-icon>
          <i class="toutiao toutiao-shouji"></i>
        </template>
      </van-field>
      <van-field
        v-model="user.code"
        type="number"
        name="code"
        placeholder="请输入验证码"
        :rules="userFormRules.code"
        maxlength="6"
      >
        <template v-slot:left-icon>
          <i class="toutiao toutiao-yanzhengma"></i>
        </template>
        <template #button>
          <!-- 倒计时组件 -->
          <van-count-down
            v-if="isCountShow"
            :time="1000 * 5"
            format="ss s"
            @finish="isCountShow = false"
          />
          <!-- native-type="button" 这属性是vant组件库自带的,他点击的时候不会触发整个表单提交,多用于发送验证码  -->
          <van-button
            v-else
            @click="onSendSms"
            native-type="button"
            class="send-sms-btn"
            round
            size="small"
            type="default"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button class="login-btn" block type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>
<script>
import { login, getSmsCode } from '../../api/user'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data() {
    return {
      user: {
        mobile: '',
        code: ''
      },
      userFormRules: {
        mobile: [
          {
            require: true,
            message: '手机号码不能为空'
          },
          {
            pattern: /^1[3578]\d{9}$/,
            message: '手机号码格式不正确'
          }
        ],
        code: [
          {
            require: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确'
          }
        ]
      },
      isCountShow: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 点击提交的时候,对数据进行校验
    async onSubmit() {
      const user = this.user
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })
      try {
        const res = await login(user)
        this.$store.commit('setUser', res.data.data) // 登录成功之后,把用户的token提交到vuex中,放到本地存储里面去
        // 清除 LayoutIndex 缓存
        this.$store.commit('removeCachePage', 'LayoutIndex')
        this.$toast.success('登录成功')
        this.$router.push(this.$route.query.redirect || '/') // 登录成功之后跳转到我的页面
      } catch (err) {
        if (err?.response?.status === 400) {
          console.log('手机号或者验证码错误')
          this.$toast.fail('手机号或验证码错误')
        } else {
          this.$toast.fail('手机号或验证码错误')
        }
      }
    },
    // 点击发送验证码的时候,对数据进行校验
    async onSendSms() {
      // 1. 校验手机号
      try {
        // validate方法用于验证单个表单项,这个地方要验证手机号,他会默认返回一个promise对象
        await this.$refs.loginForm.validate('mobile')
      } catch (err) {
        return console.log('验证失败', err)
      }
      // 2. 验证通过，显示倒计时
      this.isCountShow = true
      // 3. 请求发送验证码
      try {
        await getSmsCode(this.user.mobile)
        this.$toast('发送成功')
      } catch (err) {
        this.isCountShow = false
        if (err.response.status === 429) {
          this.$toast('发送太频繁了，请稍后重试')
        } else {
          this.$toast('发送失败，请稍后重试')
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.login-container {
  .toutiao {
    font-size: 37px;
  }
  .send-sms-btn {
    width: 152px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
  .text {
    color: #fff;
  }
}
</style>
